package com.shaozi.nc.quartz.workreport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.shaozi.data.mq.business.base.MqConsts.UserType;
import com.shaozi.data.mq.business.utils.MqUtil;
import com.shaozi.data.mq.business.base.SourceTypeConsts;
import com.shaozi.data.mq.business.bean.MqTargetUserBean;
import com.shaozi.im.protocol.core.IMConsts;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.consts.SCConsts;
import com.shaozi.nc.consts.VoConsts;
import com.shaozi.nc.data.hibVO.ReportVO;
import com.shaozi.nc.data.model.SecretaryModel;
import com.shaozi.nc.data.mongodao.SecretaryMDao;
import com.shaozi.nc.hibservice.ReportService;
import com.shaozi.nc.manage.secretary.SecretaryManage;
import com.shaozi.nc.mq.bean.base.CommonTypeExtraBean;
import com.shaozi.nc.quartz.QuartzJob;
import com.shaozi.nc.utils.SecretaryHelper;
import com.shaozi.utils.common.BeanUtils;
import com.shaozi.utils.spel.SimpleEval;

/**
 * 触发调度的时间 执行相应的业务操作
 * 
 * @author lyx
 *
 */
public class ReportQuartzJob implements QuartzJob {

	private Logger logger = Logger.getLogger(ReportQuartzJob.class);
	private String title;
	private String contentNew;
	private String contentEnd;
	@Autowired
	private BeanUtils beanUtils;
	@Autowired
	private ReportService reportService;
	@Autowired
	private SecretaryManage secretaryMgr;

	@Autowired
	private SecretaryMDao secretaryMDao;

	@SuppressWarnings("static-access")
	public ReportQuartzJob() {
		title = beanUtils.getConfig().getValue("push.msg.oa.report.title");
		contentNew = beanUtils.getConfig().getValue("push.msg.oa.report.alarm.new");
		contentEnd = beanUtils.getConfig().getValue("push.msg.oa.report.alarm.end");
	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		String companyId = context.getJobDetail().getJobDataMap().getString("companyId");
		if (StringUtils.isEmpty(companyId))
			return;
		int type = Integer.parseInt(context.getJobDetail().getJobDataMap().getString("type"));
		int alarmType = Integer.parseInt(context.getJobDetail().getJobDataMap().getString("alarmType"));
		int uid = Integer.parseInt(context.getJobDetail().getJobDataMap().getString("uid"));
		int reportId = Integer.parseInt(context.getJobDetail().getJobDataMap().getString("reportId"));
		long createTime = Long.parseLong(context.getJobDetail().getJobDataMap().getString("createTime"));

		boolean isNoNotice = Boolean.parseBoolean(context.getJobDetail().getJobDataMap().getString("isNoNotice"));
		try {
			ReportVO vo = reportService.getReport(companyId, reportId);
			if (vo == null)
				return;
			if (vo.getStatus() != VoConsts.Report.Status_3) {
				return;
			}
		} catch (SzException e1) {
			logger.error(SzException.getStackMessage(e1));
			return;
		}

		if (isNoNotice) {
			int sourceType = getSourceType(alarmType);
			SecretaryModel model = null;
			try {
				model = secretaryMDao.findByExtraId(companyId, uid + "", reportId, sourceType);
			} catch (SzException e) {
				logger.error(e);
			}
			// 表示已经发送了汇报 无需再次发送
			if (model != null) {
				return;
			}

			// List<SecretaryModel> userModels = null;
			// try {
			// userModels = secretaryMDao.getUsers(createTime, type, companyId);
			// } catch (SzException e) {
			// logger.error(e);
			// }
			// if (userModels != null && userModels.size() > 0) {
			// for (SecretaryModel model : userModels) {
			// for (MqTargetUserBean user : model.getUsers()) {
			// if (user.getUserId().equals(uid + "")) {
			// // 拦截 不再发送通知
			// return;
			// }
			// }
			// }
			// }
		}

		List<SecretaryModel> secretarys = getSecretaryModes(companyId, type, alarmType, uid, reportId);
		if (secretarys.isEmpty()) {
			return;
		}
		try {
			sendSecretary(companyId, secretarys);
		} catch (SzException e) {
			logger.error(SzException.getStackMessage(e));
		}
	}

	private void sendSecretary(String companyId, List<SecretaryModel> secretarys) throws SzException {

		secretaryMgr.handleByPushType(companyId, secretarys);
	}

	private List<SecretaryModel> getSecretaryModes(String companyId, int type, int alarmType, int uid, int reportId) {
		List<SecretaryModel> ret = new ArrayList<>();
		SimpleEval eval = new SimpleEval();

		int sourceType = getSourceType(alarmType);
		if (sourceType != SourceTypeConsts.Undefine) {
			List<MqTargetUserBean> users = new ArrayList<>();
			MqTargetUserBean user = new MqTargetUserBean(String.valueOf(uid));
			users.add(user);

			SecretaryModel secretary = new SecretaryModel();
			secretary.setSourceType(sourceType);
			secretary.setPushType(SecretaryModel.PushType_Need_Save);
			secretary.setUsers(users);
			secretary.setCompanyId(companyId);
			secretary.setTriggerUserId(String.valueOf(IMConsts.SysMemberId.Secretary_Id));
			secretary.setFromUserId(String.valueOf(IMConsts.SysMemberId.Secretary_Id));

			secretary.setTitle(title);
			Map<String, Object> params = new HashMap<>();
			params.put("dayType", getDayTypeString(type));
			params.put("reportType", getReportTypeString(type));
			String content = "";
			if (alarmType == SCConsts.ReportAlarmType.AlarmType_Begin) {
				content = contentNew;
			} else {
				content = contentEnd;
			}
			String c = (String) eval.eval(content, params);
			secretary.setContent(c);
			secretary.setType(MqUtil.getBaseSourceType(sourceType));
			secretary.setNotifyType(SecretaryHelper.getNotifyTypeFromSourceType(sourceType, UserType.Undefine));
			CommonTypeExtraBean extra = new CommonTypeExtraBean(reportId, type);
			secretary.setExtra(extra.toJsonString());
			secretary.setExtraBean(extra);
			ret.add(secretary);
		}

		return ret;
	}

	private String getReportTypeString(int type) {
		switch (type) {
		case SCConsts.ReportType.Type_Day:
			return SCConsts.ReportType.Type_Day_Str;
		case SCConsts.ReportType.Type_Week:
			return SCConsts.ReportType.Type_Week_Str;
		case SCConsts.ReportType.Type_Month:
			return SCConsts.ReportType.Type_Month_Str;
		default:
			break;
		}
		return "";
	}

	private int getSourceType(int alarmType) {
		if (SCConsts.ReportAlarmType.AlarmType_Begin == alarmType) {
			return SourceTypeConsts.OA.Report.Alarm_New;
		} else if (SCConsts.ReportAlarmType.AlarmType_End == alarmType) {
			return SourceTypeConsts.OA.Report.Alarm_End;
		} else {
			return SourceTypeConsts.Undefine;
		}
	}

	private String getDayTypeString(int type) {
		switch (type) {
		case SCConsts.ReportType.Type_Day:
			return SCConsts.ReportType.Type_Day_Cap;
		case SCConsts.ReportType.Type_Week:
			return SCConsts.ReportType.Type_Week_Cap;
		case SCConsts.ReportType.Type_Month:
			return SCConsts.ReportType.Type_Month_Cap;
		default:
			break;
		}
		return "";
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContentNew() {
		return contentNew;
	}

	public void setContentNew(String contentNew) {
		this.contentNew = contentNew;
	}

	public String getContentEnd() {
		return contentEnd;
	}

	public void setContentEnd(String contentEnd) {
		this.contentEnd = contentEnd;
	}

}
